package zhtt.derby.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import zhtt.derby.entity.Response;
import zhtt.derby.entity.User;
import zhtt.derby.service.UserService;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService service;

    @Value("${page.limit}")
    private int limit;

    @PostMapping()
    public Response create(@RequestBody User user) {
        Response response = new Response();
        try {
            service.create(user);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            return response.failure("data exists");
        } catch (Exception e) {
            e.printStackTrace();
            return response.failure("server is busy,try again later");
        }
        return response.success("create successfully");
    }

    @GetMapping()
    public Response query(@RequestParam Integer offset){
        Response response = new Response();
        try {
            List<User> userList = null;
            if(offset == null){
                userList = service.query();
            }else{
                userList = service.query(limit,offset);
            }
            response.setData(userList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

}
